var ip = ""
var payUrl = ""
$(function () {
    //移除点击事件
    $("#recharges li").unbind();
    //用户基本信息请求
    login()
    //累计充值
    countCharge()
})

//用户基本信息请求
function login() {
    slf.ajax({
        url: '/myCenter/getUserInfo',
        success: function (data) {
            //默认是游客
            var flag = false;
            if (data.res >= 1) {
                //已经登录用户
                flag = true
            }
            //充值点击事件加载
            recharge(flag, data);
        }
    });
}

//判断是微信浏览器还是其他浏览器
function is_wechat_client() {
    var ua = navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
        return true;
    } else {
        return false;
    }
}

//充值点击事件
function recharge(flag, user) {
    $('body').on('click', '#recharges li', function () {
        var first_id = $(this).children('.first_id').text();
        $('.weideng').remove();
        var money = ($(this).children('.money').text());
        //已经登录用户
        if (flag) {
            $(this).addClass('select').siblings().removeClass('select');
            //已登录
            $('body').find('.select').removeClass('select');
            ip = returnCitySN["cip"];
            /*if (is_wechat_client()) {
                //微信静默授权
                //window.location.href="\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9e4a1955fd462a63&redirect_uri=http://pay.sandcubes.com/web/slf/getOpenid&response_type=code&scope=snsapi_base&state=123#wechat_redirect\";"
                isWX(user, money, first_id);
            } else {
                isOther(user, money, first_id);
            }*/
            $.ajax({
                url: "/weixinPayNotify/isFirstCharge",
                success: function (res) {
                    if (res.obj) {
                        var htmll = '<p class="weideng">充值<span class="tuihuan"></span>元，得<span class="tuihuan"></span>立方币,额外赠送<span class="giving" style="color:red"></span>立方币</p>';
                        $('.bodw').append(htmll);
                        var discount = money * 0.12;
                        var zdiscount = parseInt(money) + parseInt(discount);
                        $('.chongzhi').text(money);
                        $('.tuihuan').text(money);
                        $('.giving').text(discount);
                        $('.zdiscount').text(zdiscount);
                        var $confirm = $('#my-confirmmoney');
                        var confirm = $confirm.data('amui.modal');
                        var onConfirm = function () {
                            $('body').find('.select').removeClass('select');
                            ip = returnCitySN["cip"];
                            isOther(user, money,first_id);
                        };
                        var onCancel = function () {
                            $('.cancel').on('click', function () {
                                $('body').find('.select').removeClass('select');
                            })
                        }
                        if (confirm) {
                            confirm.options.onConfirm = onConfirm;
                            confirm.options.onCancel = onCancel;
                            confirm.toggle(this);
                        } else {
                            $confirm.modal({
                                relatedElement: this,
                                closeViaDimmer: false,
                                onConfirm: onConfirm,
                                onCancel: onCancel
                            });
                        }
                    } else {
                        discount = money * 0;
                        zdiscount = parseInt(money) + parseInt(discount);
                        $('.chongzhi').text(money);
                        $('.tuihuan').text(money);
                        $('.giving').text(discount);
                        $('.zdiscount').text(zdiscount);
                        var $confirm = $('#my-confirmmoney');
                        var confirm = $confirm.data('amui.modal');
                        var onConfirm = function () {
                            $('body').find('.select').removeClass('select');
                            ip = returnCitySN["cip"];
                            isOther(user, money,first_id);
                        };
                        var onCancel = function () {
                            $('.cancel').on('click', function () {
                                $('body').find('.select').removeClass('select');
                            })
                        }
                        if (confirm) {
                            confirm.options.onConfirm = onConfirm;
                            confirm.options.onCancel = onCancel;
                            confirm.toggle(this);
                        } else {
                            $confirm.modal({
                                relatedElement: this,
                                closeViaDimmer: false,
                                onConfirm: onConfirm,
                                onCancel: onCancel
                            });
                        }
                    }
                }
            })
        } else {
            //未登录
            var messPrompt = "此功能仅对登录用户开放，是否需要登录？"
            $(".operationModalBody").html(messPrompt)
            $("#operationModal").modal({
            	closeViaDimmer: false,
                onConfirm: function () {
                    window.location.href = "login.html"
                },
                onCancel: function () {
                }
            })
        }
    })
}

/* 充值模态框中的取消键 */
function cancel() {
    $('.cancel').on('click', function () {
        $('body').find('.select').removeClass('select');
    })
}

/* 充值模态框中的确定键 */
function sure(user, money) {
    $(".determine").click(function () {
        $('body').find('.select').removeClass('select');
        ip = returnCitySN["cip"];
        if (is_wechat_client()) {
            //微信静默授权
            //window.location.href = "\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9e4a1955fd462a63&redirect_uri=http://pay.sandcubes.com/web/slf/getOpenid&response_type=code&scope=snsapi_base&state=123#wechat_redirect\";"
            isWX(user, money);
        } else {
            isOther(user, money);
        }

    })
}

/*H5支付*/
function isOther(user, money,first_id) {
    var userId = user.obj.userId+"&"+first_id
    slf.ajax({
        url: '/slf/h5Pay',
        type: 'post',
        param: {
            userId: userId,
            body: "立方币充值",
            money: money*100,
        },
        success: function (data) {
            if (data != undefined) {
                payUrl = data.payUrl;
                if (data.weiXinPayConfig != undefined) {
                    insertOrder(user, money, data);
                }
            }
        }
    })
}

/**
 * 公众号支付
 */
function isWX(user, money) {
    var userId = user.obj.userId;
    slf.ajax({
        url: '/slf/pay',
        type: 'post',
        param: {
            userId: userId,
            body: "立方币充值",
            money: money,
        },
        success: function (data) {
            if (data.weiXinPayConfig != undefined) {
                //新增订单
                insertOrder(user, money, data);
            }
        }
    })
}

/**
 * 新增订单
 * @param data
 */
function insertOrder(user, money, data) {

    var userId = user.obj.userId;
    //var userPhone = user.obj.phone;
    var userName = user.obj.name;
    if (userId != null && userId != undefined && userId != "") {
        slf.ajax({
            url: '/recharge/insertBySlfRecharge',
            type: 'post',
            param: {
                userName: userName,
                userId: userId,
                orderNumber: data.weiXinPayConfig.out_trade_no,
                money: money/100,
                rechargeLfb: money/100,
                shouldTotalMoney: money/100,
                payType: 1,
            },
            success: function () {
                if (is_wechat_client()) {
                    $("#payUrl").html(payUrl);
                    alert("请用微信外部浏览器打开")
                    //复制点击事件
                    /*copy()*/
                    //pay(data);
                } else {
                    window.location.href = payUrl;
                }
            }
        })
    } else {
        alert("新增订单userId为空")
    }

}

//唤起微信支付
function pay(data) {
    if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
        } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
            document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
        }
    } else {
        onBridgeReady(data);
    }
}

/*/开始支付*/
function onBridgeReady(data) {
    var timeStamp = data.data.timeStamp;
    var nonceStr = data.data.nonceStr;
    var pg = data.data.pg;
    var signType = data.data.signType;
    var paySign = data.data.paySign;
    WeixinJSBridge.invoke(
        'getBrandWCPayRequest', {
            "appId": "wx9e4a1955fd462a63",     //公众号名称，由商户传入
            "timeStamp": timeStamp,         //时间戳，自1970年以来的秒数
            "nonceStr": nonceStr, //随机串
            "package": pg,
            "signType": signType,         //微信签名方式:
            "paySign": paySign    //微信签名
        }, function (res) {
            if (res.err_msg == "get_brand_wcpay_request:ok") {
                alert("支付成功");  // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
                //回到用户订单列表
            } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
                alert("支付取消");
            } else {
                //支付失败
                alert("支付失败")
            }
        }
    );
}

/**
 * 复制链接
 */
function copy() {
    var $confirm = $('#my-copy');
    var confirm = $confirm.data('amui.modal');
    var onConfirm = function () {
        document.getElementById("payUrl").select();
        document.execCommand("copy");
        alert("复制成功,请在浏览器打开")
    };
    var onCancel = function () {
    }
    if (confirm) {
        confirm.options.onConfirm = onConfirm;
        confirm.options.onCancel = onCancel;
        confirm.toggle(this);
    } else {
        $confirm.modal({
            relatedElement: this,
            onConfirm: onConfirm,
            onCancel: onCancel
        });
    }
}

/*
function copyClick(){
    $("#copy").click(function(){
        var input = document.getElementById("url");
        input.select();
        document.execCommand("copy2");
        alert("复制成功,请在浏览器打开")
    })
}*/
function countCharge() {
    var html = "";
    $.ajax({
        url: '/weixinPayNotify/queryFirstChargeThreshold',
        success: function (data) {
            for (var i = 0; i < data.obj.length; i++) {
                html += '<li>';
                html += '<p class="money am-margin-top-sm">' + data.obj[i].first_charge_threshold_value + '</p>';
                html += '<p class="am-margin-top-sm">立方币</p>';
                html += '<span class="butt am-margin-top-sm">￥' + data.obj[i].first_charge_threshold_value + '</span>';
                html += '<span class="first_id" style="display:none">' + data.obj[i].first_charge_threshold_id + '<span>';
                html += '</li>';
            }
            $('#recharges').html(html);
        }
    });
}